__autho__ = "pengfeifu"

import json

'''
json.loads() 与eval()区别：
eval与json.loads都可以将大部分的JSON串(type:str)转成python对象,区别

1、json.loads与eval都能将s转成python中的对象，json.loads将json中的字符串转成unicode(types.UnicodeType)，eval转成了str(types.StringType)。
2、json不认单引号，json中的字符串需要用双引号包起来

'''


def file_read():
    content = ""
    try:
        with open("city.json", "rt", encoding="utf-8") as f:
            for line in f.readlines():
                content += line + "\n"
    except IOError:
        print("没有找到文件或读取文件失败")
    else:
        f.close()
    return content


# json转python对象
def json_load():
    str = '{"name": "Bill", "age": 63, "city": "Seatle"}'
    # print(type(str))
    # dictionary_json = json.loads(str)
    dictionary_json = eval(str)
    print(type(dictionary_json))
    print(dictionary_json["name"])


def json_load_file_read():
    city_json = file_read()
    print(type(city_json))  # str
    dict_json = eval(file_read())
    new_dict = {}
    print(type(dict_json))  # dict
    for city in dict_json["citys"]:
        city_id = city["id"]
        new_dict[city_id] = city['value']
    print("python对象转json", type(new_dict), new_dict)
    return new_dict


def json_to_python():
    dict_obj = json_load_file_read()

    '''
    json.dumps(obj,ensure_ascii,indent,sort_keys)，将python对象转json格式，
        ensure_ascii=False避免出现中文ascii乱码,
        indent=4将结果格式化，缩进4个字符
        sort_keys=True，自动排序
    '''
    str_json = json.dumps(dict_obj, indent=4, ensure_ascii=False,sort_keys=True)
    print("json转python对象：\n", type(str_json), str_json)


if __name__ == "__main__":
    json_to_python()
